<?php

namespace app\common\library\util;

use BlueM\Tree\Node;

/**
 * 树形数据结构操作（依赖第三方库BlueM\Tree）
 */
class Tree extends \BlueM\Tree
{
    /**
     * 根节点的值
     * @var int|float|string|null
     */
    protected $rootId = 0;

    /**
     * 主键字段标识
     * @var string
     */
    protected $idKey = 'id';

    /**
     * 父级字段标识
     * @var string
     */
    protected $parentKey = 'pid';


    /**
     * 多个节点node批量转为数组格式
     * @param array $nodes 节点数据
     * @return array
     */
    public function nodesToArray($nodes = [], $withChildren = true)
    {
        return array_map(function ($node) use ($withChildren) {
            $newNode = $node;
            if ($node instanceof Node) {
                $newNode = $node->toArray();
                if ($withChildren && $node->hasChildren()) {
                    $newNode['children'] = $this->nodesToArray($node->getChildren());
                }
            }
            return $newNode;
        }, $nodes);
    }

    /**
     * 获取某个节点的全部的祖先节点的path（从根节点往下）
     * @param Node $node 节点对象
     * @return array
     */
    public function getNodeAncestorsPath(Node $node): array
    {
        $path = $node->getAncestors();
        if (empty($path)) {
            return [];
        }
        return array_reverse($path);
    }

    /**
     * 获取某个节点的全部的祖先节点的path（从根节点往下）的label的字符串
     * @param Node $node 节点object
     * @param string $labelKey 节点的label标识
     * @param string $separator 每个节点label的分隔符
     * @return array
     */
    public function getNodeAncestorsPathString(Node $node, string $labelKey = 'title', string $separator = '/'): string
    {
        $path = $node->getAncestors();
        if (empty($path)) {
            return '';
        }
        $path = array_reverse($path);
        $pathStr = '';
        foreach ($path as $ph) {
            if ($pathStr != '') {
                $pathStr .= $separator;
            }

            if ($ph->get($labelKey)) {
                $pathStr .= $ph->get($labelKey);
            }
        }

        return $pathStr;
    }


}